<template>
  <div class="game-detail-view">
    <div class="game-detail-container">
      <!-- 头部区域 -->
      <div class="detail-header">
        <el-button class="header-back" @click="goBack">
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
        <h1 class="detail-title">游戏详情</h1>
        <p class="detail-subtitle">查看游戏记录和统计信息</p>
      </div>
      
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-state">
        <el-skeleton :rows="5" animated />
      </div>
      
      <!-- 游戏详情内容 -->
      <div v-else-if="gameDetail" class="detail-content">
        <!-- 游戏基本信息 -->
        <div class="game-basic-info">
          <div class="info-card">
            <h3 class="card-title">游戏信息</h3>
            <div class="info-grid">
              <div class="info-item">
                <span class="info-label">房间名称:</span>
                <span class="info-value">{{ gameDetail.roomName || '未知房间' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">游戏时间:</span>
                <span class="info-value">{{ formatGameDate(gameDetail.createdAt) }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">游戏时长:</span>
                <span class="info-value">{{ formatGameDuration(gameDetail.duration) }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">玩家数量:</span>
                <span class="info-value">{{ gameDetail.playerCount || 0 }}人</span>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 游戏结果 -->
        <div class="game-result-section">
          <div class="info-card">
            <h3 class="card-title">游戏结果</h3>
            <div class="result-display">
              <div :class="['result-badge', getGameResultClass(gameDetail.result)]">
                {{ getGameResultText(gameDetail.result) }}
              </div>
              <div class="result-details">
                <div class="result-item">
                  <span class="result-label">最终排名:</span>
                  <span class="result-value">{{ gameDetail.finalRank || '未知' }}</span>
                </div>
                <div class="result-item">
                  <span class="result-label">涂色面积:</span>
                  <span class="result-value">{{ gameDetail.areaPainted || 0 }} 像素</span>
                </div>
                <div class="result-item">
                  <span class="result-label">得分:</span>
                  <span class="result-value">{{ gameDetail.score || 0 }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 玩家排行榜 -->
        <div class="player-ranking-section" v-if="gameDetail.players && gameDetail.players.length > 0">
          <div class="info-card">
            <h3 class="card-title">玩家排行榜</h3>
            <div class="ranking-list">
              <div 
                v-for="(player, index) in sortedPlayers" 
                :key="player.id || index"
                class="ranking-item"
                :class="{ 'current-player': player.id === currentUserId }"
              >
                <div class="rank-number">{{ index + 1 }}</div>
                <div class="player-info">
                  <span class="player-name">{{ player.name || player.username || '未知玩家' }}</span>
                  <span v-if="player.id === currentUserId" class="me-tag">我</span>
                </div>
                <div class="player-stats">
                  <span class="area-count">{{ player.areaCount || player.areaPainted || 0 }} 像素</span>
                  <span class="player-score">{{ player.score || 0 }} 分</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 游戏统计图表 -->
        <div class="game-stats-section" v-if="gameDetail.players && gameDetail.players.length > 0">
          <div class="info-card">
            <h3 class="card-title">游戏统计</h3>
            <div class="stats-chart">
              <div class="chart-container">
                <canvas ref="statsChart" width="400" height="300"></canvas>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 错误状态 -->
      <div v-else-if="error" class="error-state">
        <el-empty description="加载游戏详情失败" :image-size="100">
          <el-button @click="loadGameDetail">重试</el-button>
        </el-empty>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElSkeleton, ElEmpty, ElButton } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { useUserStore } from '../stores/user'
import { gameAPI } from '@/api'
import { handleApiResponse } from '@/utils/request.js'

export default {
  name: 'GameDetailView',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const userStore = useUserStore()
    
    // 响应式数据
    const loading = ref(true)
    const error = ref(null)
    const gameDetail = ref(null)
    const statsChart = ref(null)
    
    // 计算属性
    const currentUserId = computed(() => userStore.user?.id)
    
    const sortedPlayers = computed(() => {
      if (!gameDetail.value?.players) return []
      return [...gameDetail.value.players].sort((a, b) => {
        const aArea = a.areaCount || a.areaPainted || 0
        const bArea = b.areaCount || b.areaPainted || 0
        return bArea - aArea
      })
    })
    
    // 格式化游戏日期
    const formatGameDate = (dateString) => {
      if (!dateString) return '未知'
      try {
        const date = new Date(dateString)
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        })
      } catch (error) {
        return '未知'
      }
    }
    
    // 格式化游戏时长
    const formatGameDuration = (duration) => {
      if (duration === null || duration === undefined) return '未知'
      const minutes = Math.floor(duration / 60000)
      const seconds = Math.floor((duration % 60000) / 1000)
      return `${minutes}分${seconds}秒`
    }
    
    // 获取游戏结果文本
    const getGameResultText = (result) => {
      if (result === 'win') return '胜利'
      if (result === 'lose') return '失败'
      if (result === 'draw') return '平局'
      return '未知'
    }
    
    // 获取游戏结果类名
    const getGameResultClass = (result) => {
      if (result === 'win') return 'game-win'
      if (result === 'lose') return 'game-lose'
      if (result === 'draw') return 'game-draw'
      return ''
    }
    
    // 加载游戏详情
    const loadGameDetail = async () => {
      const gameId = route.query.id
      if (!gameId) {
        ElMessage.error('缺少游戏ID参数')
        error.value = '缺少游戏ID参数'
        loading.value = false
        return
      }
      
      loading.value = true
      error.value = null
      
      try {
        const response = await gameAPI.getGameRecord(gameId)
        const data = handleApiResponse(response, 'data')
        
        if (data) {
          gameDetail.value = data
          console.log('游戏详情加载成功:', data)
        } else {
          error.value = '游戏记录不存在或已被删除'
          console.error('加载游戏详情失败:', response)
        }
      } catch (err) {
        error.value = '加载游戏详情失败，请重试'
        console.error('加载游戏详情失败:', err)
      } finally {
        loading.value = false
      }
    }
    
    // 返回上一页
    const goBack = () => {
      router.back()
    }
    
    // 页面加载时获取游戏详情
    onMounted(() => {
      loadGameDetail()
    })
    
    return {
      loading,
      error,
      gameDetail,
      statsChart,
      currentUserId,
      sortedPlayers,
      formatGameDate,
      formatGameDuration,
      getGameResultText,
      getGameResultClass,
      loadGameDetail,
      goBack
    }
  }
}
</script>

<style scoped>
.game-detail-view {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.game-detail-container {
  max-width: 800px;
  margin: 0 auto;
  background: white;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.detail-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 30px;
  text-align: center;
  position: relative;
}

.header-back {
  position: absolute;
  left: 30px;
  top: 50%;
  transform: translateY(-50%);
  background: rgba(255, 255, 255, 0.2);
  border: none;
  color: white;
}

.header-back:hover {
  background: rgba(255, 255, 255, 0.3);
}

.detail-title {
  font-size: 32px;
  font-weight: 700;
  margin: 0 0 10px 0;
}

.detail-subtitle {
  font-size: 16px;
  opacity: 0.9;
  margin: 0;
}

.detail-content {
  padding: 30px;
}

.loading-state,
.error-state {
  padding: 40px;
  text-align: center;
}

.info-card {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
  border: 1px solid #e9ecef;
}

.card-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin: 0 0 20px 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.info-label {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.info-value {
  font-size: 16px;
  color: #333;
  font-weight: 600;
}

.result-display {
  display: flex;
  align-items: center;
  gap: 24px;
}

.result-badge {
  font-size: 24px;
  font-weight: 700;
  padding: 12px 24px;
  border-radius: 12px;
  color: white;
  text-align: center;
  min-width: 120px;
}

.game-win {
  background: linear-gradient(135deg, #67c23a, #85ce61);
}

.game-lose {
  background: linear-gradient(135deg, #f56c6c, #f78989);
}

.game-draw {
  background: linear-gradient(135deg, #e6a23c, #ebb563);
}

.result-details {
  flex: 1;
}

.result-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.result-item:last-child {
  border-bottom: none;
}

.result-label {
  font-size: 14px;
  color: #666;
}

.result-value {
  font-size: 16px;
  color: #333;
  font-weight: 600;
}

.ranking-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.ranking-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background: white;
  border-radius: 8px;
  border: 1px solid #e9ecef;
  transition: all 0.2s ease;
}

.ranking-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.ranking-item.current-player {
  background: linear-gradient(135deg, #e3f2fd, #bbdefb);
  border-color: #2196f3;
}

.rank-number {
  width: 40px;
  height: 40px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 700;
  font-size: 18px;
}

.player-info {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 8px;
}

.player-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.me-tag {
  background: #2196f3;
  color: white;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.player-stats {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4px;
}

.area-count {
  font-size: 14px;
  color: #666;
}

.player-score {
  font-size: 16px;
  color: #333;
  font-weight: 600;
}

.stats-chart {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

.chart-container {
  width: 100%;
  max-width: 500px;
  height: 300px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .game-detail-container {
    margin: 0;
    border-radius: 0;
  }
  
  .detail-header {
    padding: 20px;
  }
  
  .header-back {
    position: static;
    transform: none;
    margin-bottom: 20px;
  }
  
  .detail-content {
    padding: 20px;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
  
  .result-display {
    flex-direction: column;
    gap: 16px;
  }
  
  .ranking-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .player-stats {
    align-items: flex-start;
  }
}
</style>
